import Vue from "vue";
import Vuex from "vuex";
import mutations from "./mutations";
import actions from "./actions";

Vue.use(Vuex);

const storegePlugin = store => {
  store.subscribe((mutation, state) => {
    // console.log(mutation)
    sessionStorage.isLogin = state.isLogin;
    localStorage.setItem("panda-mall-cart", JSON.stringify(state.cart));
    localStorage.setItem(
      "team-project-coupon-cache",
      JSON.stringify(state.couponList)
    );
  });
};
export default new Vuex.Store({
  plugins: [storegePlugin],
  state: {
    cart: localStorage.getItem("panda-mall-cart")
      ? JSON.parse(localStorage.getItem("panda-mall-cart"))
      : [],
    isLogin: sessionStorage.isLogin || false, // 登录状态
    orderList: [],
    userInfo: [{ username: "username" }],
    chosenCoupon: -1,
    couponList: localStorage.getItem("team-project-coupon-cache")
      ? JSON.parse(localStorage.getItem("team-project-coupon-cache"))
      : []
  },
  getters: {
    //购物车
    totalPrice(state) {
      return (
        state.cart.reduce((sum, item) => {
          if (item.isChecked) sum += item.price * item.amount;
          return sum;
        }, 0) * 100
      );
    },
    isAllChecked(state) {
      if (state.cart.length === 0) {
        return false;
      }
      return state.cart.every(item => item.isChecked);
    },
    //优惠券
    getCoupon(state) {
      return state.couponList.filter(item => {
        if (!item.isUsed && item.userName === state.userInfo[0].username) {
          return item;
        }
      });
    },
    getDisCoupon(state) {
      return state.couponList.filter(item => {
        if (item.isUsed && item.userName === state.userInfo[0].username) {
          return item;
        }
      });
    },
    orderTotalPrice(state) {
      return state.orderList.reduce((sum, item) => {
        sum += item.price * item.amount;
        if (state.chosenCoupon >= 0) {
          sum -= Number(state.couponList[state.chosenCoupon].valueDesc);
          return sum;
        } else {
          return sum;
        }
      }, 0);
    }
  },
  mutations,
  actions
});
